// ==UserScript==
// @name           YDict Suggest
// @namespace      http://ellab.org/
// @version        1.0
// @description    Suggest a word in Hong Kong Yahoo Dictionary if the spelling is wrong.
// @include        http://hk.dictionary.yahoo.com/noresult.html*
// ==/UserScript==

/*
Author: Angus http://angusdev.mysinablog.com/

Version history:
1.0    17-Mar-2008   First release.
*/

// extract the search word from URL
var word = document.location.href.match(/[\?|&]s=(.*)/);
if (!word) return;
word = word[1];

// find the div to hold the result, display a loading gif
var div = document.evaluate("//div[@class='estitle']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (!div) return;

div.innerHTML += "<span id='ydictsuggest'>" +
                 "<img src='%3D' " +
                 "border='0' style='vertical-align:bottom;'/>" +
                 " Loading suggestion...</span>";

GM_xmlhttpRequest({
  method: 'GET',
  url: 'http://www.google.com/search?q=' + word,
  onload: function(t) {
    var span = document.getElementById('ydictsuggest');
    if (span) {
      var res = t.responseText.match(/href="[^"]*&spell=1"/);
      var res = t.responseText.match(/&amp;q=([^&]*)&amp;spell=1/);
      if (res) {
        var suggest = res[1];
        span.innerHTML = "<span style='color:#c00;'>Did you mean:</span> " +
                         "<a style='font-weight:bold; font-style:italic;' href='/search.html?s=" + suggest + "'>" + suggest + "</a>";
      }
      else {
        span.innerHTML = "No suggestion from Google.";
      }
    }
  }
});